<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>webRtc Demo</title>
</head>
<body ng-app="user_5App" ng-controller="user_5Controller"  >
	Welcome
	<br />
	<video id="user_5,{{id}}Video" width="125" height="115" autoplay ></video>
	<video id="user_6,{{id}}Video" width="125" height="115" autoplay ></video>
	<input id="text" type="text" />
	<button ng-click="send()">发送消息</button>
	<hr />
	<button ng-click="closeWebSocket()">关闭WebSocket连接</button>
	<hr />
	<div id="message"></div>
	
</body>
<script src="js/common/jQuery-2.1.4.min.js"></script>
<script src="js/common/angular.min.js"></script>
<script src="js/user_5/config_user_5.js"></script>
<script src="js/user_5/webrtc_user_5.js"></script>
<script type="text/javascript">
var app= angular.module('user_5App', []);
app.controller('user_5Controller', function($scope) {
	$scope.id=888;
	var roles=['user_5,'+$scope.id,'user_6,'+$scope.id];
	var connections={};
	var role='user_5,'+$scope.id;
	var to='user_6,'+$scope.id;
	var websocket = new WebSocket("ws://" + window.location.host  +"/webSocket/meeting/" + role);
	var memberin;
	//连接发生错误的回调方法
	websocket.onerror = function() {
		$scope.setMessageInnerHTML("WebSocket连接发生错误");
	};
	//连接成功建立的回调方法
	websocket.onopen = function() {
		$scope.setMessageInnerHTML("WebSocket连接成功");
	};
	
	//处理到来的信令
	websocket.onmessage = function(event) {
		console.log("回调信息",event.data)
		var json = JSON.parse(event.data);
		console.log("信息",json.event)
		if(json.event=="message"){
			var message=json.data;
			var from=json.from;
			$scope.setMessageInnerHTML(from+"说："+message);
		}
		if(json.event=="role"){
			var role_to=json.data;
			con=connections[role_to];
			con.pc.close();
		}else{	 
			//建立视频会议事件
			console.log("使用websokect传输在线视频信息")
			var con;
			//发送对象
			if(connections[json.owner])con=connections[json.owner];
			//如果是一个ICE的候选，则将其加入到PeerConnection中，否则设定对方的session描述为传递过来的描述
			if (json.event === "_ice_candidate") {
				con.pc.addIceCandidate(new RTCIceCandidate(json.data.candidate));
			} else if(json.event==="msg"){
				if(json.data!=role){
					con=new Connection(role,websocket);	
					con.to=json.data;
					con.pc.addStream($scope.stream);
					connections[json.data]=con;	
				}
			}else if(json.event==="rolelist"){
				memberin=json.data;
				for(var i=0;i<memberin.length;i++){
					if(memberin[i]==role)continue;
					var con=new Connection(role,websocket);
					con.to=memberin[i];
					connections[con.to]=con;
					
				}
			}
			else{
				con.pc.setRemoteDescription(new RTCSessionDescription(
						json.data.sdp));
				// 如果是一个offer，那么需要回复一个answer
				if (json.event === "_offer") {
					//_offer
					con.pc.createAnswer(con.sendAnswerFn, function(error) {
					});
				} else {
					//_answer
				}
			}				
		}

	};

	// 获取本地音频和视频流
	var promise=navigator.getUserMedia({
        audio: true,
        video: true
	},function(stream) {
        document.getElementById(role+'Video').src = window.URL.createObjectURL(stream);
        myVid=document.getElementById(role+"Video");
    	myVid.muted=true;
    	$scope.stream=stream;
        for(var i=0;i<roles.length;i++){     //排除了自己
        	if(!connections[roles[i]])continue;
        	var con=connections[roles[i]];
            //向PeerConnection中加入需要发送的流
            con.pc.addStream(stream);
            //如果是发起方则发送一个offer信令
            if(memberin.indexOf(con.to)>=0){
            	con.start();
            }            	
        }
		},function(err) {
	         console.log("发生了以下错误: " + err.name);
	      });
	
	//连接关闭的回调方法
	websocket.onclose = function() {
		$scope.setMessageInnerHTML("WebSocket连接关闭");
	}
	//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
	window.onbeforeunload = function() {
		$scope.closeWebSocket();
	}
	//将消息显示在网页上
	$scope.setMessageInnerHTML = function(innerHTML){
		document.getElementById('message').innerHTML += innerHTML + '<br/>';
	}
	//关闭WebSocket连接
	$scope.closeWebSocket = function(){
		websocket.close();
	}
	//发送消息
	$scope.send = function(){
		var message = document.getElementById('text').value;
		websocket.send(JSON.stringify({'message':message,'role':to}));
	}

});
</script>

</html>